package org.wisigoth.chat.client.jabber;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Properties;

import org.wisigoth.chat.client.Session;
import org.wisigoth.chat.client.UserPreferences;
import org.wisigoth.chat.client.Wisigoth;
import org.wisigoth.chat.client.exceptions.AccountCreationException;
import org.wisigoth.chat.client.exceptions.WisigothRuntimeException;

public class WisigothImpl implements Wisigoth {
	private static final String CONFIG_FILE = "/wisigothjabber.properties";

	private Session session;
	private Connection connection;
	private Properties config;
	private final UserPreferences userPreferences;

	public WisigothImpl() {
		this.userPreferences = new UserPreferencesImpl();
		String host = null;
		int port = -1;
		try {
			this.config = this.loadProperties();
			host = this.config.getProperty("serverHost");
			InetAddress hostAdr = InetAddress.getByName(host);
			port = Integer.parseInt(this.config.getProperty("serverPort"));
			this.connection = new Connection(hostAdr, port);


		} catch (IOException e) {
			throw new WisigothRuntimeException(
					"Failed to initialize Wisigoth Client", e);
		}
	}


	private Properties loadProperties() throws IOException {
		InputStream input = WisigothImpl.class.getResourceAsStream(CONFIG_FILE);
		Properties props = new Properties();
		props.load(input);
		input.close();
		return props;
	}

	@Override
	public void accountCreationRequest(String login, char[] password)
			throws AccountCreationException {
		// TODO Auto-generated method stub

	}

	@Override
	public Session createSession() {
		if (this.session == null) {
			this.session = new SessionImpl(this);

		}
		return this.session;
	}

	protected Connection getConnection() {
		return this.connection;
	}

	@Override
	public UserPreferences getUserPreferences() {
		return this.userPreferences;
	}

	public static void main(String[] args) {
		WisigothImpl i = new WisigothImpl();

	}


	@Override
	public void close() {
		this.session.quitWisigoth();
		try {
			this.connection.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	



}
